﻿$(document).ready(function () {

	SetTooltips();

	OnResize();

	OnBookIDEnter();

	OnAddBookClick();
	OnEditBookClick();
	OnEditBookCancelClick();
	OnDeleteBookClick();
	OnSaveBookClick();

	OnRemovePickPersonClick();

	OnBookInfoLoadClick();
	OnBookCoverSwitchTypeClick();
	OnBookCoverSubmitClick();
	OnEditBookCoverClick();
	OnEditBookCoverCancelClick();
	OnViewingBookCoverClick();
	OnBookCoverUploadComplete();

	OnToggleSubscribersListClick();
	OnSubscribersActionWireUp();

	OnAdminPanelIconEnterLeave();
	OnAdminPanelEnterLeave();

	OnOwnerPickClick();
	OnTagsPickClick();
	OnSetReaderPickClick();

	OnEscKeyDown();

	OnPopupWindowCloseClick();

	InitDefaultTextHandler();
});

/* Tooltips configuring */
function SetTooltips() {

	$(".bookFooter").personInfoTooltip(".peopleName");
	$("#bookEditingContainer").personInfoTooltip(".peopleName");
	$(".bookFooter").personTimeTooltip(".clockIcon");
	$(".bookFooter").commonTooltip(".historyReaderIcon,.currentReaderIcon,.crossIcon,.backPointerIcon,.pointerIcon,.waitingListActiveIcon,.undo,.redo,.smallEditIcon");
	$(".commandBar").commonTooltip(".addIcon,.editIcon,.deleteIcon, .saveIcon,.cancelIcon,#uploadBookInfoIcon");
}
/* End */

/* Resizing */

function OnResize() {

	$(window).resize(function () {

		if (!$("#mask").is(":hidden")) {

			var displayingFormSelector = "";

			if (!$("#bookCoverFormContainer").is(":hidden")) {

				displayingFormSelector = "#bookCoverFormContainer";
			}
			else if (!$("#bookViewerContainer").is(":hidden")) {

				displayingFormSelector = "#bookViewerContainer";
			}

			ShowHideMaskForm("show", displayingFormSelector);
		}
	});
}
/* End */

/* Book management functions */

function OnAddBookClick() {

	$(".addIcon").on("click", function () {

		var form = $("#bookEditingForm");

		form.attr("action", form.data("add"));

		ClearBookEditingForm();

		RemoveRestoreDefaultText("restore");

		ShowHideBookEditingForm("show");

		var editingMaskWidth = $("#booksContainer").outerWidth(true) + "px";
		var editingMaskHeight = $("#booksContainer").outerHeight(false) + "px";

		$("#bookEditingMask").css({ width: editingMaskWidth, height: editingMaskHeight }).fadeIn();
	});
}

function OnEditBookClick() {

	$(".editIcon").on("click", function () {

		var currentBook = $(this).parent().parent().parent().find(".bookContent");

		var bookEditingContainer = $("#bookEditingContainer");

		bookEditingContainer.find("#hfBookID").val(currentBook.find("input[name = 'bookID']").val());
		bookEditingContainer.find("#txtTitle").val(currentBook.find(".bookInfo .title").text());
		bookEditingContainer.find("#txtAuthor").val(currentBook.find(".bookInfo .author").text());

		bookEditingContainer.find("#txtDescription").val(currentBook.find(".bookDescription .formattedDescription").text());
		bookEditingContainer.find("#txtISBN").val(currentBook.find(".bookISBN").text());
		bookEditingContainer.find("#txtEAN").val(currentBook.find(".bookEAN").text());
		bookEditingContainer.find("#imgCover").attr("src", currentBook.find(".bookCover").attr("src"));
		bookEditingContainer.find("#hfOwnerID").val(currentBook.find(".ownerText .peopleName").data("person-id"));

		var trimmedOwner = $.trim(currentBook.find(".ownerText").text());

		var owner = bookEditingContainer.find("#txtOwner").text(trimmedOwner);

		if ($(owner).text() != $(owner).data("default")) {
			$(owner).addClass("peopleName").data("person-id", $("#hfOwnerID").val());
			$("#removePickIcon").showInlineBlock();
		}

		bookEditingContainer.find("#hfImageID").val("");

		$("#txtISBN,#txtISBN").trigger("change");

		var form = bookEditingContainer.find("form");
		form.attr("action", form.data("update"));

		RemoveRestoreDefaultText("restore");

		ShowHideBookEditingForm("show");

		var editingMaskWidth = $("#booksContainer").outerWidth(true) + "px";
		var editingMaskHeight = $("#booksContainer").outerHeight(false) + "px";

		$("#bookEditingMask").css({ width: editingMaskWidth, height: editingMaskHeight }).show();
	});
}

function OnEditBookCancelClick() {

	$("#bookEditingContainer .cancelIcon").on("click", function () {

		var bookEditingContainer = $("#bookEditingContainer");

		bookEditingContainer.slideUp("normal");

		$("#bookEditingMask").hide();

		ClearValidationSummary($("#bookValidationSummary"));

		$("#uploadBookInfoIcon").removeClass("previewIcon").addClass("inactivePreviewIcon");

		ClearBookEditingForm();

		RemoveRestoreDefaultText("restore");
	});
}


function OnDeleteBookClick() {

	$("#booksContainer .deleteIcon").on("click", function () {

		var form = $(this).parent().parent().parent().find("[name=bookDeleteForm]");

		$("#btnConfirm").on("click", function () {
			form.submit();
		});

		$("#btnCancelConfirmation").on("click", function () {

			ShowHideMaskForm("hide", "#confirmationPopup");

		});

		$("#confirmationPopup .message").text("Are you sure you wish to delete this book?");

		ShowHideMaskForm("show", "#confirmationPopup");

	});
}

function OnSaveBookClick() {

	$(".saveIcon").on("click", function () {

		RemoveRestoreDefaultText("remove");

		var currentPage = $("#mainPagination .selectedItem").text();

		if (currentPage == "") {
			currentPage = 1;
		}

		$("#hfCurrentPage").val(currentPage);

		$("#bookEditingForm").submit();

		RemoveRestoreDefaultText("restore");
	});
}

function OnRemovePickPersonClick() {
	$("#removePickIcon").on("click", function () {
		$(this).hide();
		$("#hfOwnerID").val(0);
		$("#txtOwner").text($("#txtOwner").data("default")).data("person-id", "").removeClass("peopleName");
	});
}

function OnBookInfoLoadClick() {

	$("#uploadBookInfoIcon").on("click", function () {

		if (!$(this).hasClass("inactiveAmazonIcon")) {
			var requestData = new Object();
			requestData.bookID = "";

			if (IsBookNumberValid("#txtISBN", false)) {

				requestData.bookID = $("#txtISBN").val();
			} else if (IsBookNumberValid("#txtEAN", true)) {

				requestData.bookID = $("#txtEAN").val();
			}

			if (requestData.bookID != "") {

				ShowHideLoadingSpinner("show", "#mediumSpinner");

				$.ajax({
					url: $(this).data("postback"),
					type: "POST",
					data: requestData,
					complete: function (xhr, textStatus) { OnBookInfoLoadComplete(xhr, textStatus); }
				});
			}
		}
	});
}
function OnBookInfoLoadComplete(xhr, textStatus) {

	ShowHideLoadingSpinner("hide", "#mediumSpinner");

	if (textStatus == "success") {

		var data = $.parseJSON(xhr.responseText);

		if (data.ImageID != "") {

			var frameData = new Object();
			frameData.ImageID = data.ImageID;

			$("#frImageID").contents().find("body").text(JSON.stringify(frameData));
			$("#frImageID").trigger("load");
		}

		$("#txtTitle").val(data.Title);
		$("#txtAuthor").val(data.Authors);
		$("#txtDescription").val(data.Description);
		$("#txtISBN").val(data.ISBN);
		$("#txtEAN").val(data.EAN);
	}
	else {

		alert(GetErrorMsg(textStatus));
	}
}
function ClearBookEditingForm() {

	$("#hfBookID, #hfImageID, #txtTitle, #txtAuthor, #txtDescription, #txtISBN, #txtEAN").val("");

	$("#hfPersonID").val(0);

	$("#txtOwner").text($("#txtOwner").data("default")).data("person-id", "").removeClass("peopleName");

	$("#removePickIcon").hide();

	$("#imgCover").attr("src", $("#imgCover").data("default-src"));
}

function ShowHideBookEditingForm(mode) {

	var bookEditingContainer = $("#bookEditingContainer");

	if (mode == "show") {

		$(bookEditingContainer).slideDown("normal");
	}
	else if (mode == "hide") {
		$(bookEditingContainer).slideUp("normal");
	}
}
function OnTagsPickClick() {

	$("#tagsPickIcon").on("click", function () {

		ShowTagsPicker();
	});
}
function OnOwnerPickClick() {

	$("#ownerPickIcon").on("click", function () {

		SetPerson($("#txtOwner").text(), $("#hfOwnerID").val());

		OnBtnChooseClick(function () {
			var pickedPersonID = GetPickedPersonID();
			$("#hfOwnerID").val(pickedPersonID);
			$("#removePickIcon").showInlineBlock(pickedPersonID);
			$("#txtOwner").text(GetSelectedPersonName()).data("person-id", pickedPersonID).addClass("peopleName");
		});
		ShowPersonPicker();
	});
}
function OnSetReaderPickClick() {

	$(".bookFooter").on("click", ".peopleWrapper .smallEditIcon", function () {

		var eventSource = $(this);

		var readerContainer = $(eventSource).closest(".peopleWrapper").find(".reader");

		var reader = $(readerContainer).find(".personName");

		SetPerson($(reader).text(), $(reader).data("person-id"));

		ShowPersonPicker();

		OnBtnChooseClick(function () {

			var bookFooter = $(eventSource).closest(".bookContent");

			var ajaxParams = new Object();

			ajaxParams.requestData = new Object();

			ajaxParams.requestData.personID = GetPickedPersonID();
			ajaxParams.requestData.state = $(eventSource).data("state");

			ajaxParams.requestUrl = $(eventSource).data("postback");

			ajaxParams.requestData.bookID = $(bookFooter).find("input[name='bookID']").val();
			ajaxParams.requestData.historyListMode = $(bookFooter).find("ul[data-list-name='historyList']").data("list-mode");
			ajaxParams.requestData.waitingListMode = $(bookFooter).find("ul[data-list-name='waitingList']").data("list-mode");

			GenerateSubscribersAjaxRequest(ajaxParams, bookFooter);
		});
	});

}
/* End */

/* Common functions */

function OnBookIDEnter() {

	$("#txtISBN,#txtEAN").on("change input", function () {

		var uploadIcon = $("#uploadBookInfoIcon");

		if (IsBookNumberValid("#txtISBN", false) || IsBookNumberValid("#txtEAN", true)) {

			if (!$(uploadIcon).hasClass("amazonIcon")) {

				$(uploadIcon).toggleClass("inactiveAmazonIcon amazonIcon");
			}
		}
		else if ($(uploadIcon).hasClass("amazonIcon")) {

			$(uploadIcon).toggleClass("inactiveAmazonIcon amazonIcon");
		}
	});
}

function IsBookNumberValid(bookNumberField, isEan) {

	if (isEan) {
		return $(bookNumberField).val().match("[0-9]{12}[0-9xX]{1}");

	} else {
		return $(bookNumberField).val().match("[0-9]{9}[0-9xX]{1}");
	}
}


function OnEscKeyDown() {

	$(document).on("keydown", function (e) {

		if (e.keyCode == 27) {

			ShowHideLoadingSpinner("hide", "#mediumSpinner");

			var currentPopup = $(".popupWindow:visible");

			ShowHideMaskForm("hide", currentPopup);
		}
	});
}

function ClearValidationSummary(validationSummary) {

	var list = $(validationSummary).find("ul");

	list.empty();

	list.addClass("validation-summary-valid").removeClass("validationSummaryError");
}

/* Popup windows functions */

function OnPopupWindowCloseClick() {

	$(".popupWindow .deleteIcon,#btnAlertOk").on("click", function () {

		var currentPopup = $(this).closest(".popupWindow");

		ShowHideLoadingSpinner("hide", "#mediumSpinner");

		ShowHideMaskForm("hide", currentPopup);

		$("#imageUploadValidationSummary").hide();
	});
}

/* End */

/* Book preview functions */

function OnViewingBookCoverClick() {

	$("#booksContainer").on("click", ".previewCover", function () {

		ShowHideLoadingSpinner("show", "#mediumSpinner");

		var bookIdentifiers = $(this).parent().parent().find(".bookISBN,.bookEAN");

		var elem = document.getElementById("bookViewer");

		var viewer = new google.books.DefaultViewer(elem);

		viewer.load("ISBN:" + $(bookIdentifiers).first().text(), OnPreviewNotFound, function () { OnPreviewLoadSuccess(viewer); });
	});
}

function OnPreviewLoadSuccess(viewer) {

	ShowHideMaskForm("show", "#bookViewerContainer");

	ShowHideLoadingSpinner("hide", "#mediumSpinner");

	viewer.resize();
}

function OnPreviewNotFound() {

	ShowHideLoadingSpinner("hide", "#mediumSpinner");

	$("#alertPopup .message").text("Book preview is not available");

	ShowHideMaskForm("show", "#alertPopup");
}

/* End */

/* Subscribers functions */
function OnToggleSubscribersListClick() {

	$(".bookFooter").on("click", ".listIconContainer span", function () {
		ToggleSubscribersList($(this).parent().siblings("ul"));
		$(this).toggleClass("closedListIcon openedListIcon");
	});
}

function ToggleSubscribersList(list) {

	var inactiveSubscribers = $(list).children("li:first-child").siblings();

	inactiveSubscribers.toggleClass("hidden");

	WriteDataListMode(list);
}

function WriteDataListMode(list) {

	var mode = parseInt($(list).data("list-mode"));
	if (mode == 0) {

		$(list).data("list-mode", 1);

	}
	else {

		$(list).data("list-mode", 0);
	}
}

function OnSubscribersActionWireUp() {

	$(".bookFooter").on("click", ".waitingListActiveIcon, .currentReaderIcon, .historyReaderIcon, .pointerIcon, .backPointerIcon, .crossIcon, .undo, .redo",
	function () {

		var bookFooter = $(this).closest(".bookFooter");
		var ajaxParams = new Object();
		ajaxParams.requestData = new Object();

		if (!$(this).hasClass("waitingListActiveIcon")) {

			ajaxParams.requestData.personID = $(this).closest("li").find(".peopleName").data("person-id");
		}

		if ($(this).hasClass("undo")) {

			ajaxParams.requestData.isUndo = true;
		}
		else if ($(this).hasClass("redo")) {

			ajaxParams.requestData.isUndo = false;
		}

		ajaxParams.requestData.bookID = $(this).closest(".bookContent").find("input[name='bookID']").val();
		ajaxParams.requestData.historyListMode = $(this).closest(".bookFooter").find("ul[data-list-name='historyList']").data("list-mode");
		ajaxParams.requestData.waitingListMode = $(this).closest(".bookFooter").find("ul[data-list-name='waitingList']").data("list-mode");
		ajaxParams.requestData.state = $(this).data("state");
		ajaxParams.requestData.subscriptionSet = $(this).closest("li").data("subscription-set");

		ajaxParams.requestUrl = $(this).data("postback");

		GenerateSubscribersAjaxRequest(ajaxParams, bookFooter);

	});
}

function GenerateSubscribersAjaxRequest(ajaxParams, target) {

	$.ajax({
		url: ajaxParams.requestUrl,
		type: "POST",
		data: ajaxParams.requestData,
		complete: function (xhr, textStatus) { OnSubscribersActionWireUpComplete(xhr, textStatus, target); }
	});

}

function OnSubscribersActionWireUpComplete(xhr, textStatus, bookFooterElement) {

	if (textStatus == "success") {

		$(bookFooterElement).find(".bookDetailsContainer").replaceWith(xhr.responseText);

	}
	else {
		var errorMsg = GetErrorMsg(textStatus);
		alert(errorMsg);
	}
}
/* End */

/* Book cover functions */
function OnEditBookCoverClick() {

	$("#preloadedCoverPlace").on("click", function () {

		ShowHideMaskForm("show", "#bookCoverFormContainer");

	});
}

function OnEditBookCoverCancelClick() {

	$("#btnUploadCancel").on("click", function () {

		ShowHideMaskForm("hide", "#bookCoverFormContainer");
		$("#imageUploadValidationSummary").hide();
	});
}

function OnBookCoverSubmitClick() {

	$("#bookCoverForm").on("submit", function () {

		if ($("#fuImage").val() != "" || $("#txtUrl").val() != "") {

			$("#fuImage,#txtUrl").hide();

			$("#rbUpload,#lblUpload,#rbUrl,#lblUrl,#btnUploadConfirm,#btnUploadCancel").attr("disabled", "disabled");

			ShowHideLoadingSpinner("show", "#loadingImageBar");
		}

		$("#imageUploadValidationSummary").hide();
	});
}

function OnBookCoverSwitchTypeClick() {

	$("#rbUpload, #rbUrl").on("change", function (e) {

		if ($("#rbUpload").is(":visible")) {

			$("#imageUploadValidationSummary").hide();
		}

		$("#fuImage").val("");
		$("#txtUrl").val("");

		$("#txtUrl, #fuImage").toggle();
	});
}


function OnBookCoverUploadComplete() {

	$("#frImageID").load(function () {

		var data = $.parseJSON($(this).contents().find("body").text());

		if (data != null) {

			if (data.ImageID != null) {

				var src = data.ImageUrl;

				$("#hfImageID").val(data.ImageID);

				$("#bookEditingContainer img.bookCover").attr("src", src);

				ShowHideMaskForm("hide", "#bookCoverFormContainer");

				$("#imageUploadValidationSummary").hide();
			} else if (data.Errors != null) {

				var errorsList = $("#imageUploadValidationSummary ul");

				var errorItems = "";

				$.each(data.Errors, function (key, value) {
					errorItems = errorItems + "<li>" + value + "</li>";

				});

				$(errorsList).html(errorItems);

				$("#imageUploadValidationSummary").show();
			}
		}

		ShowHideLoadingSpinner("hide", "#loadingImageBar");
		$("#fuImage").show();
		$("#rbUpload,#lblUpload,#rbUrl,#lblUrl,#btnUploadConfirm,#btnUploadCancel").removeAttr("disabled");
	});
}
/* End */

/* Default text functions */
function InitDefaultTextHandler() {
	$("#txtTitle, #txtAuthor, #txtDescription, #txtISBN, #txtEAN").on("focus focusout",

		function (e) {
			switch (e.type) {
				case "focus":
					DefaultTextHandler("remove", e.target);

					break;
				case "focusout":
					DefaultTextHandler("restore", e.target);

					break;
			}
		});
}

function RemoveRestoreDefaultText(mode) {

	$("#txtTitle, #txtAuthor, #txtDescription, #txtISBN, #txtEAN").each(

		function () {
			DefaultTextHandler(mode, this);
		});
}

function DefaultTextHandler(mode, target) {

	if (mode == "remove") {

		if (target.value == $(target).data("default")) {
			target.value = "";
		}
	}
	else if (mode == "restore") {

		if (target.value == "") {
			target.value = $(target).data("default");
		}
	}
}
/* End */

function OnAdminPanelIconEnterLeave() {

	$(".bookFooter").on("mouseenter mouseleave", ".adminPanelIcon", function (e) {

		var visibleAdminPanel = $(".adminPanel:visible");
		var adminPanel = $(this).parent().find(".adminPanel");

		if (e.type == "mouseenter") {

			if (visibleAdminPanel != adminPanel) {
				$(visibleAdminPanel).hide();

				$(adminPanel).show();
			}
		}
		else {

			$(adminPanel).data("hiding-timer", setTimeout(function () {

				$(adminPanel).hide();

			}, 500));
		}
	});
}

function OnAdminPanelEnterLeave() {

	$(".bookFooter").on("mouseenter mouseleave", ".adminPanel", function (e) {

		var panel = $(this);

		if (e.type == "mouseleave" && !$(e.relatedTarget).hasClass("adminPanelIcon")) {

			$(panel).data("hiding-timer", setTimeout(function () {

				$(panel).hide();

			}, 500));
		}
		else if (e.type = "mouseenter") {

			clearTimeout($(panel).data("hiding-timer"));
		}
	});
}